package com.example.yz.happywoker.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.example.yz.happywoker.GlobalData;
import com.example.yz.happywoker.lib.Constants;
import org.greenrobot.eventbus.EventBus;
import java.util.List;


public class PollingService extends Service {
    public static final String ACTION = Constants.PACKNAMEPOLLING + ".PollingService";
    private static final String TAG = "PollingServiceYZ";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new PollingThread().start();
        return START_STICKY;
    }

    class PollingThread extends Thread {
        @Override
        public void run() {
            Log.d(TAG, "定时执行一次轮询");
            AVUser user = AVUser.getCurrentUser();
            if(user == null){
                return;
            }
            AVQuery<AVObject> avQuery = new AVQuery<>("RobMyOrderList");
            avQuery.whereEqualTo("robWokerPhone", user.getUsername());
            avQuery.whereLessThan("State", "5");
            avQuery.whereGreaterThan("State", "1");
            avQuery.findInBackground(new FindCallback<AVObject>() {
                @Override
                public void done(List<AVObject> lister, AVException e) {
                    Log.e("listernull",""+lister+"为空");
                    if (lister!=null && lister.size()!=0) {
                        for (AVObject avObject : lister) {
                          if(avObject.getString("State")!=null) {
                                String status = avObject.getString("State");
                                if (!status.equals("3") && GlobalData.IdG == null) {
                                    GlobalData.IdG = avObject.getObjectId();
                                    GlobalData.MyObjectIdG = avObject.get("OrderNumber").toString();  //获取订单的ID
                                    EventBus.getDefault().post(status);
                                    Log.e(TAG, "EventBus post"+"到这里了");
                                }
                            }

                        }
                   }
                }
            });
        }
    }

}

